package com.timmy.bluetooth.scan;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备扫描类
 */
public class DeviceScan extends DeviceScanManager {

    public static final int REQUEST_OPEN_BLE = 10;

    /**
     * 默认扫描时间{s}
     */
    private int period = 10;

    private boolean mScanning = false;
    private List<String> addrList;
    private BluetoothAdapter mBluetoothAdapter;
    private Context ctx;
    private DeviceScanCallback callback;
    private Handler handler;
    //private UserGroupManager userGroupManager;
    //private DBManager dbManager;


    public void ScanInit(Context ctx, DeviceScanCallback callback, int period_s) {
        Log.i("开始搜索", "开始搜索");

        //上下文
        this.ctx = ctx;

        addrList = new ArrayList<>();
        handler = new Handler();

        //扫描超时时间
        period = period_s;

        this.callback = callback;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // dbManager = new DBManager(ctx);

    }

    /**
     * 取消扫描
     */
    public void cancelScan() {
        scanLeDevice(false);
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        //判断蓝牙是否开启
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();         //开启蓝牙
        } else {
            //userGroupManager = new UserGroupManager();
            scanLeDevice(true);
        }
    }

    /**
     * 是否正在扫描
     *
     * @return
     */
    public boolean isScanning() {
        return mScanning;
    }

    public void ScanDeInt() {
        if (mScanning) {
            cancelScan();
        }

        if (mBluetoothAdapter != null) {
            mBluetoothAdapter = null;
        }

        if (addrList != null) {
            addrList.clear();
            addrList = null;
        }
    }


    //开始搜索蓝牙设备
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mScanning = true;

            if (addrList != null) {
                addrList.clear();
            }

            if (mBluetoothAdapter != null) {
                //开始扫描，扫描所有附近的蓝牙设备，扫描结果在回调：onLeScan
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            }

            //延迟5s执行 delay 任务
            handler.postDelayed(delay, 1000 * period);

            if (callback != null) {
                callback.onScanStart();         //空方法
            }

        } else {

            mScanning = false;
            if (mBluetoothAdapter != null) {
                //由于扫描是耗电操作，完成后尽早结束扫描。
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }

            if (callback != null) {
                callback.onScanEnd();       //停止搜索,回调方法
            }

            handler.removeCallbacks(delay);
        }
    }

    /**
     * 第一次是延迟5s执行
     */
    Runnable delay = new Runnable() {
        @Override
        public void run() {
            scanLeDevice(false);
        }
    };

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    // Log.i("扫描的回调", "onLeScan: " + device.toString());            rssi 信号大小

                    //蓝牙设备信息的bean类
                    DeviceInfo deviceInfo = new DeviceInfo();

                    if (cmp(device) && select(device)) {

                        deviceInfo.setRssi(rssi);               //信号
                        String address = device.getAddress();
                        deviceInfo.setAddress(address);
                        deviceInfo.setName(device.getName() + "-" + getId(address));

                        if (callback != null) {
                            callback.onDevice(deviceInfo);      //回调方法
                        }

                        addrList.add(device.getAddress());
                    }
                }

            };

    //选择设备
    private boolean select(BluetoothDevice device) {

        if (device.getName() == null) {
            return false;
        }

        return true;
    }


    //过滤重复的蓝牙设备地址
    private boolean cmp(BluetoothDevice device) {
        if (addrList == null) {
            addrList = new ArrayList<>();
        }

        int i = 0;
        while (i < addrList.size()) {
            String str = addrList.get(i);
            if (device.getAddress().equals(str.trim()))
                return false;
            i++;
        }
        return true;
    }


    //将设备地址的前6位赋值给设备，便于区分
    private String getId(String addr) {
        return (addr.subSequence(9, 11) + addr.substring(12, 14) + addr.substring(15, 17)).toString();
    }
}
